package middleware

import (
	"fmt"
	"os"
	"runtime/pprof"
	"time"
)

type PprofFile struct {
}

var minioFileManager = MinioFileManager{}

func (upf PprofFile) Do() {
	now := time.Now()
	go func() {
		fileName := fmt.Sprintf("cpu-%v.prof", now.Format("20060102-150405"))
		tmpFile, _ := os.CreateTemp("", fileName)
		defer os.Remove(tmpFile.Name()) // 使用后清理
		defer tmpFile.Close()

		if err := pprof.StartCPUProfile(tmpFile); err != nil {
			logger.ERROR(fmt.Sprintf("StartCPUProfile error : %v", err))
		}
		time.Sleep(time.Second * 5) // 采集5秒
		pprof.StopCPUProfile()
		if _, err := tmpFile.Seek(0, 0); err != nil {
			logger.ERROR(fmt.Sprintf("mem tmpFile.Seek error : %v", err))
		}
		minioFileManager.UploadFile(fileName, tmpFile)
	}()

	go func() {
		fileName := fmt.Sprintf("mem-%v.prof", now.Format("20060102-150405"))
		tmpFile, _ := os.CreateTemp("", fileName)
		defer os.Remove(tmpFile.Name()) // 使用后清理
		defer tmpFile.Close()
		pprof.WriteHeapProfile(tmpFile)
		if _, err := tmpFile.Seek(0, 0); err != nil {
			logger.ERROR(fmt.Sprintf("mem tmpFile.Seek error : %v", err))
		}
		minioFileManager.UploadFile(fileName, tmpFile)
	}()
}
